<template>
  <div class="driver-training-detail">
    <el-card class="detail-card">
      <template #header>
        <div class="card-header">
          <el-button @click="goBack" icon="ArrowLeft">返回</el-button>
          <span class="title">司机 {{ driverId }} 培训建议详情</span>
        </div>
      </template>
      
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="6" animated />
      </div>
      
      <div v-else-if="driverData" class="detail-content">
        <!-- 司机基本信息 -->
        <el-descriptions title="司机信息" :column="3" border>
          <el-descriptions-item label="司机ID">
            {{ driverData.driver_id }}
          </el-descriptions-item>
          <el-descriptions-item label="培训类型总数">
            {{ driverData.recommendation_types.length }}
          </el-descriptions-item>
          <el-descriptions-item label="培训建议总数">
            {{ driverData.total_count }}
          </el-descriptions-item>
        </el-descriptions>

        <!-- 培训类型汇总 -->
        <el-card class="summary-card" style="margin-top: 20px;">
          <template #header>
            <span class="content-title">培训类型汇总</span>
          </template>
          <div class="training-types-summary">
            <el-tag 
              v-for="type in driverData.recommendation_types" 
              :key="type"
              :type="getTrainingTypeColor(type)"
              size="large"
              style="margin: 5px;"
            >
              {{ type }}
            </el-tag>
          </div>
        </el-card>

        <!-- 所有培训建议列表 -->
        <el-card class="recommendations-card" style="margin-top: 20px;">
          <template #header>
            <span class="content-title">所有培训建议</span>
          </template>
          <el-table :data="driverData.all_recommendations" style="width: 100%">
            <el-table-column label="培训类型" width="120">
              <template #default="scope">
                <el-tag :type="getTrainingTypeColor(scope.row.recommendation_type)">
                  {{ scope.row.recommendation_type }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="培训内容" show-overflow-tooltip>
              <template #default="scope">
                <el-tooltip 
                  :content="formatTrainingContent(scope.row.recommendation_content)" 
                  placement="top" 
                  :show-after="500"
                >
                  <span class="training-content">
                    {{ getTrainingContentPreview(scope.row.recommendation_content) }}
                  </span>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column label="优先级" width="100">
              <template #default="scope">
                <el-tag :type="getPriorityColor(scope.row.priority)">
                  {{ getPriorityText(scope.row.priority) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="状态" width="100">
              <template #default="scope">
                <el-tag :type="getStatusColor(scope.row.status)">
                  {{ getStatusText(scope.row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="创建时间" width="180">
              <template #default="scope">
                {{ formatTime(scope.row.created_time) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150">
              <template #default="scope">
                <el-button type="primary" size="small" @click="viewTrainingDetail(scope.row.id)">
                  查看详情
                </el-button>
                <el-button 
                  v-if="scope.row.status === 0" 
                  type="success" 
                  size="small" 
                  @click="pushTrainingRecommendation(scope.row.id)"
                >
                  推送
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>

        <!-- 统计信息 -->
        <el-card class="stats-card" style="margin-top: 20px;">
          <template #header>
            <span class="content-title">统计信息</span>
          </template>
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="stat-item">
                <h4>优先级分布</h4>
                <div class="stat-content">
                  <el-tag 
                    v-for="(count, priority) in driverData.priority_summary" 
                    :key="priority"
                    :type="getPriorityColor(parseInt(priority))"
                    style="margin: 3px;"
                  >
                    {{ getPriorityText(parseInt(priority)) }}: {{ count }}
                  </el-tag>
                </div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="stat-item">
                <h4>状态分布</h4>
                <div class="stat-content">
                  <el-tag 
                    v-for="(count, status) in driverData.status_summary" 
                    :key="status"
                    :type="getStatusColor(parseInt(status))"
                    style="margin: 3px;"
                  >
                    {{ getStatusText(parseInt(status)) }}: {{ count }}
                  </el-tag>
                </div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="stat-item">
                <h4>操作</h4>
                <div class="stat-content">
                  <el-button 
                    v-if="hasUnpushedRecommendations" 
                    type="success" 
                    @click="pushAllRecommendations"
                  >
                    推送全部未推送
                  </el-button>
                  <el-button type="primary" @click="refreshData">
                    刷新数据
                  </el-button>
                </div>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </div>
      
      <div v-else class="error-container">
        <el-empty description="未找到司机培训数据" />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'
import { evaluationAPI } from '@/api/evaluation'

const route = useRoute()
const router = useRouter()

const driverData = ref(null)
const loading = ref(true)

const driverId = computed(() => route.params.driverId)

// 获取司机培训数据
function loadDriverTrainingData() {
  const storedData = sessionStorage.getItem('driverTrainingData')
  console.log('从sessionStorage获取的数据:', storedData)
  
  if (storedData) {
    try {
      driverData.value = JSON.parse(storedData)
      console.log('解析后的司机培训数据:', driverData.value)
      console.log('培训建议列表:', driverData.value?.all_recommendations)
      
      // 验证数据完整性
      if (driverData.value?.all_recommendations) {
        driverData.value.all_recommendations.forEach((rec, index) => {
          console.log(`培训建议 ${index + 1}:`, {
            id: rec.id,
            type: rec.recommendation_type,
            status: rec.status,
            priority: rec.priority
          })
        })
      }
    } catch (e) {
      console.error('解析司机培训数据失败:', e)
      ElMessage.error('数据格式错误')
    }
  } else {
    console.error('sessionStorage中没有找到司机培训数据')
    ElMessage.error('未找到司机培训数据')
  }
  loading.value = false
}

// 查看单个培训建议详情
function viewTrainingDetail(id) {
  console.log('点击查看详情，ID:', id)
  console.log('当前司机数据:', driverData.value)
  console.log('所有培训建议:', driverData.value?.all_recommendations)
  
  if (!id) {
    ElMessage.error('无效的培训建议ID')
    return
  }
  
  // 验证ID是否存在
  const recommendation = driverData.value?.all_recommendations?.find(r => r.id === id)
  if (!recommendation) {
    console.error('未找到培训建议:', id)
    ElMessage.error(`未找到ID为 ${id} 的培训建议`)
    return
  }
  
  console.log('找到培训建议:', recommendation)
  router.push(`/training/detail/${id}`)
}

// 推送单个培训建议
async function pushTrainingRecommendation(id) {
  try {
    const response = await evaluationAPI.pushTrainingRecommendation(id)
    if (response.data && response.data.message) {
      ElMessage.success('培训建议推送成功')
      // 更新本地数据状态
      const recommendation = driverData.value.all_recommendations.find(r => r.id === id)
      if (recommendation) {
        recommendation.status = 1
        // 重新计算状态汇总
        driverData.value.status_summary = getStatusSummary(driverData.value.all_recommendations)
      }
    } else {
      ElMessage.error(response.data?.error || '推送失败')
    }
  } catch (error) {
    console.error('推送培训建议失败:', error)
    ElMessage.error('推送失败')
  }
}

// 推送所有未推送的培训建议
async function pushAllRecommendations() {
  const unpushedRecommendations = driverData.value.all_recommendations.filter(rec => rec.status === 0)
  if (unpushedRecommendations.length === 0) {
    ElMessage.warning('没有未推送的培训建议')
    return
  }

  try {
    for (const recommendation of unpushedRecommendations) {
      const response = await evaluationAPI.pushTrainingRecommendation(recommendation.id)
      if (!response.data || !response.data.message) {
        throw new Error(`推送培训建议 ${recommendation.id} 失败`)
      }
      recommendation.status = 1
    }
    
    // 重新计算状态汇总
    driverData.value.status_summary = getStatusSummary(driverData.value.all_recommendations)
    ElMessage.success(`成功推送 ${unpushedRecommendations.length} 条培训建议`)
  } catch (error) {
    console.error('推送培训建议失败:', error)
    ElMessage.error('推送失败')
  }
}

// 刷新数据
async function refreshData() {
  loading.value = true
  try {
    const response = await evaluationAPI.getTrainingRecommendations(driverId.value)
    if (response.data && response.data.data) {
      // 重新构建司机数据
      const recommendations = response.data.data
      const summaryRecord = {
        driver_id: parseInt(driverId.value),
        recommendation_types: [...new Set(recommendations.map(r => r.recommendation_type))],
        all_recommendations: recommendations.sort((a, b) => new Date(b.created_time) - new Date(a.created_time)),
        latest_recommendation: recommendations[0],
        total_count: recommendations.length,
        status_summary: getStatusSummary(recommendations),
        priority_summary: getPrioritySummary(recommendations)
      }
      driverData.value = summaryRecord
      sessionStorage.setItem('driverTrainingData', JSON.stringify(summaryRecord))
      ElMessage.success('数据已刷新')
    }
  } catch (error) {
    console.error('刷新数据失败:', error)
    ElMessage.error('刷新数据失败')
  } finally {
    loading.value = false
  }
}

// 返回
function goBack() {
  router.back()
}

// 格式化时间
function formatTime(timeStr) {
  if (!timeStr) return ''
  const date = new Date(timeStr)
  return date.toLocaleString('zh-CN')
}

// 获取培训内容预览
function getTrainingContentPreview(content) {
  if (!content) return '暂无内容'
  
  const cleanContent = content
    .replace(/^#{1,6}\s*/gm, '')
    .replace(/\*\*(.*?)\*\*/g, '$1')
    .replace(/\*(.*?)\*/g, '$1')
    .replace(/^###\s*/gm, '')
    .replace(/^####\s*/gm, '')
    .replace(/^-\s*/gm, '• ')
    .trim()
  
  if (cleanContent.length > 50) {
    return cleanContent.substring(0, 50) + '...'
  }
  return cleanContent
}

// 格式化培训内容
function formatTrainingContent(content) {
  if (!content) return '暂无培训内容'
  
  if (typeof content === 'string') {
    return content
      .replace(/^#{1,6}\s*/gm, '')
      .replace(/\*\*(.*?)\*\*/g, '$1')
      .replace(/\*(.*?)\*/g, '$1')
      .replace(/^###\s*/gm, '')
      .replace(/^####\s*/gm, '')
      .replace(/^-\s*/gm, '• ')
      .trim()
  }
  
  return String(content)
}

// 获取培训类型颜色
function getTrainingTypeColor(type) {
  switch (type) {
    case '服务态度':
      return 'success'
    case '驾驶技术':
      return 'info'
    case '车辆状况':
      return 'warning'
    case '沟通能力':
      return 'primary'
    case '时间观念':
      return 'danger'
    default:
      return 'info'
  }
}

// 获取优先级颜色
function getPriorityColor(priority) {
  switch (priority) {
    case 1:
      return 'info'
    case 2:
      return 'warning'
    case 3:
      return 'danger'
    default:
      return 'info'
  }
}

// 获取状态颜色
function getStatusColor(status) {
  switch (status) {
    case 0:
      return 'info'
    case 1:
      return 'success'
    case 2:
      return 'warning'
    case 3:
      return 'success'
    default:
      return 'info'
  }
}

// 获取优先级文本
function getPriorityText(priority) {
  switch (priority) {
    case 1:
      return '低'
    case 2:
      return '中'
    case 3:
      return '高'
    default:
      return '未知'
  }
}

// 获取状态文本
function getStatusText(status) {
  switch (status) {
    case 0:
      return '未推送'
    case 1:
      return '已推送'
    case 2:
      return '已查看'
    case 3:
      return '已完成'
    default:
      return '未知'
  }
}

// 获取状态汇总
function getStatusSummary(recommendations) {
  const statusCounts = {}
  recommendations.forEach(rec => {
    const status = rec.status
    statusCounts[status] = (statusCounts[status] || 0) + 1
  })
  return statusCounts
}

// 获取优先级汇总
function getPrioritySummary(recommendations) {
  const priorityCounts = {}
  recommendations.forEach(rec => {
    const priority = rec.priority
    priorityCounts[priority] = (priorityCounts[priority] || 0) + 1
  })
  return priorityCounts
}

// 检查是否有未推送的培训建议
const hasUnpushedRecommendations = computed(() => {
  return driverData.value && driverData.value.all_recommendations.some(rec => rec.status === 0)
})

onMounted(() => {
  loadDriverTrainingData()
})
</script>

<style scoped>
.driver-training-detail {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.detail-card {
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  align-items: center;
  gap: 10px;
}

.title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.loading-container {
  padding: 20px;
}

.detail-content {
  padding: 20px 0;
}

.summary-card,
.recommendations-card,
.stats-card {
  border-radius: 8px;
}

.content-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.training-types-summary {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.training-content {
  display: inline-block;
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: #606266;
  font-size: 14px;
  line-height: 1.4;
}

.training-content:hover {
  color: #409EFF;
  cursor: pointer;
}

.stat-item {
  text-align: center;
  padding: 10px;
}

.stat-item h4 {
  margin: 0 0 10px 0;
  color: #606266;
  font-size: 14px;
}

.stat-content {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 5px;
}

.error-container {
  padding: 40px;
  text-align: center;
}
</style> 